package com.lyeducation.services.video;

import com.lyeducation.controllers.dto.UpdVideoDto;
import com.lyeducation.controllers.dto.VideoDto;
import com.lyeducation.core.base.SystemProperties;
import com.lyeducation.core.base.TokenConstants;
import com.lyeducation.core.video.VideoQueryEnum;
import com.lyeducation.core.video.VideoService;
import com.lyeducation.entities.course.ChapterEntity;
import com.lyeducation.entities.course.VideoEntity;
import com.lyeducation.entities.course.middle.ChapterVideoEntity;
import com.lyeducation.entities.course.middle.VideoImageEntity;
import com.lyeducation.entities.system.SysImageEntity;
import com.lyeducation.repository.VideoRepository;
import com.lyeducation.security.config.SecurityPrincipalContext;
import com.lyeducation.services.base.BaseDateServiceImpl;
import com.lyeducation.util.HttpUtils;
import com.lyeducation.util.StringUtils;
import com.lyeducation.util.controllerUtil.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.sql.Timestamp;
import java.util.*;

@Slf4j
@Service
public class VideoServiceImpl extends BaseDateServiceImpl<VideoEntity> implements VideoService {
    @Autowired
    private VideoRepository videoRepository;
    @Autowired
    SystemProperties systemProperties;

    @Override
    public Collection<VideoEntity> findData(VideoQueryEnum videoQueryEnum) {
        String sql = null;
        if (VideoQueryEnum.MOSTCOMMENT.equals(videoQueryEnum)) {
            sql = "SELECT * FROM VideoEntity as v ORDER BY v.createTime DESC LIMIT 5";
            return videoRepository.list(sql);
        } else if (VideoQueryEnum.NEW.equals(videoQueryEnum)) {
            sql = "SELECT * FROM video as v ORDER BY v.createTime DESC LIMIT 5";
            return videoRepository.findByNativeQuery(sql, null);
        }
        return null;
    }

    @Override
    public VideoEntity addVideoByCallBack(Map<String, Object> ossCallbackBody) {
        VideoEntity videoEntity = new VideoEntity();
        //        videoEntity.setName(ossCallbackBody.get("object").toString());
        //        videoEntity.setLength(Long.valueOf(ossCallbackBody.get("size").toString()));
        //        videoEntity.setMimeType(ossCallbackBody.get("mimeType").toString());
        //        videoEntity.setRelativePath(ossCallbackBody.get("url").toString());
        return videoRepository.saveOrUpdate(videoEntity);
    }

    @Override
    public void addVideo(VideoDto videoDto) {

        VideoEntity videoEntity = new VideoEntity();
        SysImageEntity imageEntity = new SysImageEntity();
        videoEntity.setId(videoDto.getObject());
        imageEntity.setId(TokenConstants.generateUserId());
        videoEntity.setName(videoDto.getName());
        videoEntity.setSize(videoDto.getSize());
        videoEntity.setMimeType(videoDto.getMimeType());
        videoEntity.setVideoAccessRole(videoDto.getVideoAccessRole().getValue());
        videoEntity.setUrl(videoDto.getUrl());
        videoEntity.setSort(videoDto.getSort());
        if (StringUtils.trimToNull(videoDto.getImgBase64()) != null) {
            File file =
                    HttpUtils.setBase64Data(
                            "videoImage/" + videoEntity.getId(), imageEntity.getId(), videoDto.getImgBase64());
            String imgUrl =
                    systemProperties.getProjectAddress() + "/" + file.toURI().getPath().split("classes/")[1];
            videoEntity.setImgUrl(imgUrl);
            imageEntity.setUrl(file.getPath());
            imageEntity.setImgUrl(imgUrl);
            imageEntity.setSize(file.length());
            imageEntity.setName(file.getName());
            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            imageEntity.setCreateTime(timestamp);
            imageEntity.setCreateId(SecurityPrincipalContext.getUserDetailsImpl().getId());
            imageEntity.setUpdateId(SecurityPrincipalContext.getUserDetailsImpl().getId());
            imageEntity.setUpdateTime(timestamp);
            String imageMimeType = videoDto.getImgBase64().split(",")[0].split(";")[0].split(":")[1];
            imageEntity.setMimeType(imageMimeType);
            videoRepository.save(imageEntity);
        }
        videoEntity = videoRepository.save(videoEntity);

        ChapterVideoEntity chapterVideo = new ChapterVideoEntity();
        chapterVideo.setChapterId(videoDto.getChapterId());
        chapterVideo.setVideoId(videoEntity.getId());
        videoRepository.save(chapterVideo);
        VideoImageEntity videoImageEntity = new VideoImageEntity();
        videoImageEntity.setImageId(imageEntity.getId());
        videoImageEntity.setVideoId(videoEntity.getId());
        videoRepository.save(videoImageEntity);

    }

    @Override
    public JsonResult selVideoByChartId(String chapterId, int pageNo, int pageSize) {
        List<ChapterVideoEntity> chapterVideoEntities = videoRepository.findByFiled(ChapterVideoEntity.class, "chapterId", chapterId);
        List<String> videoIds = new ArrayList<>();
        if (chapterVideoEntities != null && chapterVideoEntities.size() > 0) {
            for (ChapterVideoEntity chapterVideoEntity : chapterVideoEntities) {
                videoIds.add(chapterVideoEntity.getVideoId());
            }
            String sql = "select * from video where isDelete=false and id in(:idlist)";
            Map<String, Object> map = new HashMap<>();
            map.put("idlist", videoIds);
            return JsonResult.putSuccess(
                    videoRepository.findPageByNativeQueryFileds(sql, map, pageNo, pageSize));
        }
        return JsonResult.putFail("未查询到数据");
    }

    @Override
    public boolean delVideoByChapterId(String chapterId) {
        LinkedHashMap conditionParams = new LinkedHashMap<>();
        conditionParams.put("chapterId", chapterId);
        List<ChapterVideoEntity> chapterVideoEntities = videoRepository.findByFileds(ChapterVideoEntity.class, conditionParams);
        List<String> videoIds = new ArrayList<>();
        for (ChapterVideoEntity chapterVideoEntity : chapterVideoEntities) {
            videoIds.add(chapterVideoEntity.getVideoId());
        }
        conditionParams.clear();
        conditionParams.put("ids", videoIds);
        Map valueMap = new HashMap();
        valueMap.put("isDelete", true);
        String hql = "as v set v.isDelete=:isDelete where v.id in (:ids)";
        if (videoRepository.updateFileds(VideoEntity.class, hql, conditionParams, valueMap) < 1) {
            return false;
        }
        return true;
    }

    @Override
    public JsonResult updVideoMsg(UpdVideoDto videoDto) {
        VideoEntity videoEntity = videoRepository.findById(videoDto.getId());
        if (videoEntity != null) {
            if (StringUtils.trimToNull(videoDto.getChapterId()) != null) {
                ChapterEntity chapterEntity = videoRepository.findById(ChapterEntity.class, videoDto.getChapterId());
                if (chapterEntity != null) {
                    List<ChapterVideoEntity> chapterVideoEntities = videoRepository.findByFiled(ChapterVideoEntity.class, "videoId", videoEntity.getId());
                    if (chapterVideoEntities.size() != 1) {
                        return JsonResult.putFail("视频只允许在一个章节下");
                    } else {
                        videoRepository.remove(chapterVideoEntities.get(0));
//                    Map map = new HashMap();
//                    map.put("videoId", videoDto.getId());
//                    map.put("chapterId", videoDto.getId());
//                    videoRepository.deleteByMap(ChapterVideoEntity.class, map);
                    }
                    ChapterVideoEntity chapterVideoEntity = new ChapterVideoEntity();
                    chapterVideoEntity.setChapterId(chapterEntity.getId());
                    chapterVideoEntity.setVideoId(videoEntity.getId());
                    videoRepository.save(chapterVideoEntity);
                }
            }
            if (StringUtils.trimToNull(videoDto.getImgBase64()) != null) {
                List<VideoImageEntity> videoImageEntities = videoRepository.findByFiled(VideoImageEntity.class, "videoId", videoEntity.getId());
                if (videoImageEntities.size() > 1) {
                    return JsonResult.putFail("视频截图个数错误:" + videoImageEntities.size());
                }
                SysImageEntity imageEntity = null;
                if (videoImageEntities.size() == 1) {
                    imageEntity = videoRepository.findById(SysImageEntity.class, videoImageEntities.get(0).getImageId());
                }
                if (imageEntity == null) {
                    imageEntity = new SysImageEntity();
                    Timestamp timestamp = new Timestamp(System.currentTimeMillis());
                    imageEntity.setCreateTime(timestamp);
                    imageEntity.setCreateId("");
                    imageEntity.setUpdateId("");
//                    imageEntity.setCreateId(SecurityPrincipalContext.getUserDetailsImpl().getId());
//                    imageEntity.setUpdateId(SecurityPrincipalContext.getUserDetailsImpl().getId());
                    imageEntity.setUpdateTime(timestamp);
                    imageEntity.setId(TokenConstants.generateUserId());
                    VideoImageEntity videoImageEntity = new VideoImageEntity();
                    videoImageEntity.setImageId(imageEntity.getId());
                    videoImageEntity.setVideoId(videoEntity.getId());
                    videoRepository.save(videoImageEntity);
                } else {
                    File delFile = new File(imageEntity.getUrl());
                    delFile.delete();
                }
                File file =
                        HttpUtils.setBase64Data(
                                videoEntity.getId(), imageEntity.getId(), videoDto.getImgBase64());
                String imgUrl =
                        systemProperties.getProjectAddress()
                                + "/"
                                + file.toURI().getPath().split("classes/")[1];
                String imageMimeType = videoDto.getImgBase64().split(",")[0].split(";")[0].split(":")[1];
                videoEntity.setImgUrl(imgUrl);
                imageEntity.setMimeType(imageMimeType);
                imageEntity.setUrl(file.getPath());
                imageEntity.setImgUrl(imgUrl);
                imageEntity.setSize(file.length());
                imageEntity.setName(file.getName());
                videoRepository.save(imageEntity);
            }
            videoEntity.setName(videoDto.getName());
            videoEntity.setSort(videoDto.getSort());
            videoEntity.setVideoAccessRole(videoDto.getVideoAccessRole().getValue());

        if (videoRepository.update(videoEntity) != null) {
            return JsonResult.putSuccess(videoEntity);
        }
            return JsonResult.putFail();
        }
        return JsonResult.putFail("查询不到该视频");
    }
}
